<?php
namespace app\index\pointscontroller;

use think\Request;
use phpException\SuccessException;

use app\index\model\Words;
use phpException\ErrorException;	

class Word
{
	//查看指定文章 及文章下的评论
	public function word_article(){
		try{
			//获取文章id
			$id = request()->param('id');

			//实例化方法并且调用
			$word = new Words;
			$data = $word->get_word($id);
			
			if(empty($data)){
				throw new ErrorException("没有数据");
			}
			
			//查看该文章下几个人评论
			throw new SuccessException('数据返回成功',200,$data);
		}catch(Exception $e){
			throw new ErrorException($e);
		}
		
	}

	//发布文章
	public function word_add()
	{
		try{
			$info = \Request::header();
			$token = $info['token'];
			//登录状态才能登录
			if(!token_exists($token)){
				throw new ErrorException('尚未登录博客',401);
			}//q3ualD9vdxjlo1p
			$data = request()->param();

			//调用验证器
			$validate = new \app\index\validate\Wordv;
			//抛出异常
			if (!$validate->check($data)) {
        		throw new ErrorException($validate->getError(),412);
    		}

			$word = new Words;
			$user = \Cache::get($token);
			$uid = $user['id'];
			$data = [
			    'title'  =>  $data['title'],
			    'content' =>  $data['content'],
			    'uid'  =>  $uid,
			];
			$n = $word->add($data);
			if($n){
				throw new SuccessException("添加成功",200);
			}
		}catch(Exception $e){
			throw new ErrorException($e);
		}
	}

	//删除文章及评论
	public function word_del(){
		try{
			$info = \Request::header();
			$token = $info['token'];
			//登录状态才能登录
			if(!token_exists($token)){
				throw new ErrorException('尚未登录博客',401);
			}
			$id = request()->param('id');
			
			$words = new Words;
			//获取文章id 前端传递的文章id
			$word = $words->get_word($id);
			if(empty($word)) {
				throw new ErrorException('该文章已被删除',410);
			}
			$user = \Cache::get($token);
			//检测当前用户
			$uid = $user['id'];

			if($word['uid'] != $uid) {
				throw new ErrorException('用户不匹配',401);
			}
			//调用方法 删除
			$n = $words->word_delete($id);
			
			if($n){
				throw new SuccessException("删除成功",200);
			} else {
				throw new ErrorException("删除失败",412);
			}
		}catch(Exception $e){
			throw new ErrorException($e);
		}
	}

}